package net.j4love.es.example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author he peng
 * @create 2017/11/26 15:41
 * @see
 */
public class DocumentApiTest extends BaseTest {

    private static final Logger LOG = LogManager.getLogger(DocumentApiTest.class);

    @Test
    public void buklApi() throws Exception {
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        // either use client#prepare, or use Requests# to directly build index/delete requests
        bulkRequest.add(client.prepareIndex("twitter", "tweet", "1")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                        .endObject()
                )
        );

        bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "another post")
                        .endObject()
                )
        );

        BulkResponse bulkResponse = bulkRequest.get();
        if (bulkResponse.hasFailures()) {
            // process failures by iterating through each bulk response item
        }
    }

    @Test
    public void multiGetApi() throws Exception {
        MultiGetRequestBuilder multiGetRequestBuilder = super.client.prepareMultiGet();
        multiGetRequestBuilder.add("girl","lolita","1");
        multiGetRequestBuilder.add("girl","lolita","2");
        multiGetRequestBuilder.add("girl","lolita","3");
        MultiGetResponse multiGetItemResponses = multiGetRequestBuilder.get();

        for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
            GetResponse response = itemResponse.getResponse();
            if (response.isExists()) {
                String json = response.getSourceAsString();
                LOG.info("multi get api response json ===> {} " , json);
            }
        }

    }

    @Test
    public void updateApi() throws Exception {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("girl").type("lolita").id("1");
        Map<String,Object> source = new HashMap<>(4);
        source.put("girl_name","唐静");
        source.put("interests",new String[]{"tennis" , "music"});

        updateRequest.doc(source,XContentType.JSON);
        super.client.update(updateRequest).get();
    }

    // junit 内不能操作线程
    @Test
    public void deleteByQueryAsyncApi() throws Exception {
        DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchQuery("girl_name", "唐"))
                .source("persons")
                .execute(new ActionListener<BulkByScrollResponse>() {

                    @Override
                    public void onResponse(BulkByScrollResponse response) {
                        LOG.info("delete by query api response ===> {} , deleted {} "
                                , response , response.getDeleted());
                    }

                    @Override
                    public void onFailure(Exception e) {
                        LOG.error(e.getMessage() , e);
                    }
                });
    }

    @Test
    public void deleteByQueryApi() throws Exception {
        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(super.client)
                .filter(QueryBuilders.matchQuery("girl_name", "唐静"))
                .source("girl").get();

        long deleted = response.getDeleted();
        LOG.info("delete by query api response ===> {} , deleted {} " , response , deleted);

    }

    @Test
    public void indexApi() throws Exception {
        Map<String,Object> source = new HashMap<>(4);
        source.put("girl_name","为伱而描眉画唇");
        source.put("age","23");
        source.putIfAbsent("say", "傻宝宝");
        source.put("interests",new String[]{"photo" , "study"});

        IndexRequestBuilder indexRequestBuilder =
                super.client.prepareIndex("girl", "lolita", "3");
        indexRequestBuilder = indexRequestBuilder.setSource(source, XContentType.JSON);
        IndexResponse indexResponse = indexRequestBuilder.get();

        LOG.info("index response ===> {} " , indexResponse);
    }

    @Test
    public void getApi() throws Exception {
        GetResponse response = client.prepareGet("twitter", "tweet", "1").get();

        LOG.info("get response ===> {} " , response);

    }

    @Test
    public void deleteApi() throws Exception {
        DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();
        LOG.info("delete response ===> {} " , response);
    }

}
